package com.xiaoxing.gongqiju.mvp.ui.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.dothantech.lpapi.IAtBitmap;
import com.dothantech.lpapi.LPAPI;
import com.dothantech.printer.IDzPrinter;
import com.hss01248.frescopicker.FrescoIniter;
import com.hss01248.photoouter.PhotoCallback;
import com.hss01248.photoouter.PhotoUtil;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.base.BaseConstants;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.jess.arms.utils.CProgressDialogUtils;
import com.jess.arms.utils.LogUtils;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.SpinnerStyle;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.xiaoxing.gongqiju.R;
import com.xiaoxing.gongqiju.R2;
import com.xiaoxing.gongqiju.di.component.DaggerLiaoCheng_GongQiJu_RuKuCaoZuoComponent;
import com.xiaoxing.gongqiju.di.module.LiaoCheng_GongQiJu_RuKuCaoZuoModule;
import com.xiaoxing.gongqiju.mvp.contract.LiaoCheng_GongQiJu_RuKuCaoZuoContract;
import com.xiaoxing.gongqiju.mvp.presenter.LiaoCheng_GongQiJu_RuKuCaoZuoPresenter;
import com.xiaoxing.gongqiju.mvp.ui.adapter.LiaoCheng_GongQiJu_RuKuCaoZuoAdapter;
import com.xiaoxing.gongqiju.mvp.ui.entity.Instore;
import com.xiaoxing.gongqiju.mvp.ui.entity.LiaoCheng_GongQiJu_RuKu;
import com.xiaoxing.gongqiju.mvp.ui.entity.LiaoCheng_GongQiJu_RuKuCaoZuo;
import com.xiaoxing.gongqiju.mvp.ui.utils.PrinterUtil;
import com.xw.repo.XEditText;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import me.iwf.photopicker.utils.ProxyTools;
import me.jessyan.armscomponent.commonres.utils.BottomDialogUtil;
import me.jessyan.armscomponent.commonres.utils.ToolbarUtils;
import me.jessyan.armscomponent.commonres.view.RecycleViewDivider;
import me.jessyan.armscomponent.commonsdk.core.RouterHub;
import okhttp3.RequestBody;

import static com.jess.arms.utils.Preconditions.checkNotNull;


@Route(path = RouterHub.GONGQIJU_LIAOCHENG_ACTIVITY_LIAO_CHENG_GONG_QI_JU_RU_KU_CAO_ZUO)
public class LiaoCheng_GongQiJu_RuKuCaoZuoActivity extends BaseActivity<LiaoCheng_GongQiJu_RuKuCaoZuoPresenter> implements LiaoCheng_GongQiJu_RuKuCaoZuoContract.View, OnRefreshListener, LiaoCheng_GongQiJu_RuKuCaoZuoAdapter.ILiaoCheng_GongQiJu_RuKuCaoZuoAdapter, PrinterUtil.PrinterI {


    private static boolean mIsNeedDemo = true;
    @BindView(R2.id.empty_text)
    TextView empty_text;
    @BindView(R2.id.empty_image)
    ImageView empty_image;

    @BindView(R2.id.empty)
    View mEmptyLayout;
    @BindView(R2.id.recyclerView)
    RecyclerView mRecyclerView;
    @BindView(R2.id.refreshLayout)
    RefreshLayout mRefreshLayout;
    @BindView(R2.id.xet_ru_ku_shu_liang)
    XEditText xetRuKuShuLiang;
    @BindView(R2.id.xet_cang_wei)
    XEditText xetCangWei;
    @BindView(R2.id.btn_cha_xun_cang_wei)
    Button btnChaXunCangWei;
    @BindView(R2.id.img_zhao_pian)
    ImageView imgZhaoPian;
    PrinterUtil mPrinterUtil;
    private LiaoCheng_GongQiJu_RuKuCaoZuoAdapter mAdapter;
    private List<LiaoCheng_GongQiJu_RuKuCaoZuo.DataBean> mDataBeanList = new ArrayList<>();
    private LiaoCheng_GongQiJu_RuKu.DataBean item;
    private BottomDialogUtil mBottomDialogUtilShare;
    private String mPic = "";
    private String printData = "";
    private int mCurrentDialogStyle = com.qmuiteam.qmui.R.style.QMUI_Dialog;

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerLiaoCheng_GongQiJu_RuKuCaoZuoComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .liaoCheng_GongQiJu_RuKuCaoZuoModule(new LiaoCheng_GongQiJu_RuKuCaoZuoModule(this))
                .build()
                .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_liao_cheng__gong_qi_ju__ru_ku_cao_zuo; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {

        ToolbarUtils.initToolbarTitleBack(this, getString(R.string.activity_liao_cheng__gong_qi_ju__ru_ku_cao_zuo));
        item = (LiaoCheng_GongQiJu_RuKu.DataBean) getIntent().getExtras().getSerializable("item");
        PhotoUtil.init(this, new FrescoIniter());
        mPrinterUtil = new PrinterUtil(this);
        mPrinterUtil.setPrinterI(this);
        IDzPrinter.Factory.getInstance().init(this, mPrinterUtil.mCallback);

        initRefreshLayout();
        initRecyclerView();
        initEmpty();
    }

    private void initEmpty() {
        empty_image.setImageResource(R.drawable.ic_empty);
        empty_text.setTextColor(Color.parseColor("#D8D8D8"));
        empty_text.setText("暂无数据");
    }

    private void initRecyclerView() {
        mRecyclerView.setLayoutManager(new LinearLayoutManager(LiaoCheng_GongQiJu_RuKuCaoZuoActivity.this));
        mRecyclerView.addItemDecoration(new RecycleViewDivider(this, LinearLayoutManager.VERTICAL, 10, Color.parseColor("#EEEEEE")));

        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView.setAdapter(mAdapter = new LiaoCheng_GongQiJu_RuKuCaoZuoAdapter(LiaoCheng_GongQiJu_RuKuCaoZuoActivity.this, mDataBeanList, this));

        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
            }
        });
    }

    private void initRefreshLayout() {
        mRefreshLayout.setRefreshHeader(new
                ClassicsHeader(this).setSpinnerStyle(SpinnerStyle.FixedBehind).setPrimaryColorId(R.color.public_colorPrimary).setAccentColorId(android.R.color.white));
        mRefreshLayout.setOnRefreshListener(this);
        mRefreshLayout.setEnableRefresh(false);
        mRefreshLayout.autoRefresh();
        mRefreshLayout.setEnableLoadMore(false);
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {

        mRefreshLayout.finishRefresh();
        mEmptyLayout.setVisibility(View.GONE);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode != 0)
            PhotoUtil.onActivityResult(this, requestCode, resultCode, data);
    }

    @Override
    public void getLiaoCheng_GongQiJu_RuKuCaoZuoDataSuccess(LiaoCheng_GongQiJu_RuKuCaoZuo entityList) {

        if (entityList != null && entityList.getData() != null && entityList.getData().size() > 0) {
            mDataBeanList.clear();
            mDataBeanList.addAll(entityList.getData());
            mAdapter.notifyDataSetChanged();
            mEmptyLayout.setVisibility(View.GONE);
            mRecyclerView.setVisibility(View.VISIBLE);
        } else {
            mEmptyLayout.setVisibility(View.VISIBLE);
            mRecyclerView.setVisibility(View.GONE);
        }

    }

    @Override
    public void instoreDataSuccess(Instore entityList) {

        showMessage(entityList.getMessage());
        if (!TextUtils.isEmpty(entityList.getData()) && (Integer.parseInt(entityList.getData()) > 0)) {
            printData = entityList.getData();
            printBigQRcodeOriention(printData);
        }

    }

    private void printBigQRcodeOriention(String content) {

        // 得到 IDzPrinter 对象
        IDzPrinter printer = IDzPrinter.Factory.getInstance();
        // 连接配对的第一个打印机对象
        printer.connect(IDzPrinter.Factory.getFirstPrinter());
        // 创建 IAtBitmap 绘图对象
        IAtBitmap api = IAtBitmap.Factory.createInstance();
        // 开始绘图任务，传入参数(页面宽度, 页面高度)
        api.setItemHorizontalAlignment(LPAPI.ItemAlignment.LEFT);
        api.setItemOrientation(180);

        api.startJob(50 * 100, 50 * 100);//48, 50
//        api.setItemOrientation(180);

        // 开始一个页面的绘制，绘制二维码

        api.drawText("序号:" + content, 30 * 100, 8 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
        api.draw2DQRCode(content, 14 * 100, 11 * 100, 20 * 100);//  9, 10, 20,30

        // 结束绘图任务
        api.endJob();
        // 打印
        printer.print(api, null);

    }

    @Override
    public void showLoading() {
        CProgressDialogUtils.showProgressDialog(this);
    }

    @Override
    public void hideLoading() {
        CProgressDialogUtils.cancelProgressDialog(this);
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.makeText(this, message);

    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }

    @OnClick(R2.id.btn_cha_xun_cang_wei)
    public void onViewClicked() {
        mDataBeanList.clear();
        mAdapter.notifyDataSetChanged();
        mEmptyLayout.setVisibility(View.VISIBLE);
        mRecyclerView.setVisibility(View.GONE);
        getLiaoCheng_GongQiJu_RuKuCaoZuoList();
    }

    @OnClick(R2.id.img_zhao_pian)
    public void imgZhaoPian() {
        xuanZeTuPian();
    }

    private void xuanZeTuPian() {
        LinearLayout root = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.sales_client_bottom_dialog_pai_zhao, null);
        Button btn_xiang_ce = root.findViewById(me.iwf.photopicker.R.id.btn_xiang_ce);
        Button ben_xiang_ji = root.findViewById(me.iwf.photopicker.R.id.ben_xiang_ji);
        Button btn_qu_xiao = root.findViewById(me.iwf.photopicker.R.id.btn_qu_xiao);
        btn_qu_xiao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mBottomDialogUtilShare != null)
                    mBottomDialogUtilShare.dismissDiaolog();
            }
        });
        btn_xiang_ce.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mBottomDialogUtilShare != null)
                    mBottomDialogUtilShare.dismissDiaolog();

                PhotoUtil.begin()
                        .setNeedCropWhenOne(false)
                        .setNeedCompress(false)
                        .setMaxSelectCount(1)

                        .start(LiaoCheng_GongQiJu_RuKuCaoZuoActivity.this, 33, ProxyTools.getShowMethodInfoProxy(new PhotoCallback() {
                            @Override
                            public void onFail(String msg, Throwable r, int requestCode) {
                            }

                            @Override
                            public void onSuccessSingle(String originalPath, String compressedPath, int requestCode) {
//
                                try {
                                    createMaterialForInstoreAuto(compressedPath);
                                } catch (Exception e) {
                                    e.printStackTrace();

                                }
                            }

                            @Override
                            public void onSuccessMulti(List<String> originalPaths, List<String> compressedPaths, int requestCode) {
//                                refresh1(originalPaths);

                            }

                            @Override
                            public void onCancel(int requestCode) {
                            }
                        }));
            }
        });
        ben_xiang_ji.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mBottomDialogUtilShare != null)
                    mBottomDialogUtilShare.dismissDiaolog();
                PhotoUtil.statusBarColor = R.color.public_black;
                PhotoUtil.titleBarColor = R.color.public_black;
                PhotoUtil.cropAvatar(true).setCropMuskOvalFalse()
                        .start(LiaoCheng_GongQiJu_RuKuCaoZuoActivity.this, 23, ProxyTools.getShowMethodInfoProxy(new PhotoCallback() {
                            @Override
                            public void onFail(String msg, Throwable r, int requestCode) {
                            }

                            @Override
                            public void onSuccessSingle(String originalPath, String compressedPath, int requestCode) {
                                try {
                                    createMaterialForInstoreAuto(compressedPath);
                                } catch (Exception e) {
                                    e.printStackTrace();

                                }
                            }

                            @Override
                            public void onSuccessMulti(List<String> originalPaths, List<String> compressedPaths, int requestCode) {
                            }

                            @Override
                            public void onCancel(int requestCode) {
                            }
                        }));
            }
        });

        mBottomDialogUtilShare = new BottomDialogUtil(LiaoCheng_GongQiJu_RuKuCaoZuoActivity.this, root);
        mBottomDialogUtilShare.showDiaolog();

    }

    private void createMaterialForInstoreAuto(String compressedPath) throws Exception {
        mPic = ArmsUtils.bitmapToString(compressedPath);
//        SPUtil.putString(CangKuActivity.this, "zhaopian", imgStr);
        Bitmap bitmap = BitmapFactory.decodeFile(compressedPath);
        imgZhaoPian.setImageBitmap(bitmap);
    }

    private void getLiaoCheng_GongQiJu_RuKuCaoZuoList() {
        HashMap<String, String> map = new HashMap<>();
        map.put("userid", mSharedPreferencesHelper.getString(BaseConstants.UID));
        mPresenter.getLiaoCheng_GongQiJu_RuKuCaoZuoList(map);
    }

    @Override
    public void ruKu(LiaoCheng_GongQiJu_RuKuCaoZuo.DataBean item) {
        if (TextUtils.isEmpty(mPic)) {
            showMessage("请先拍照");
            return;
        }
        if (TextUtils.isEmpty(getRuKuShuLiang())) {
            showMessage("请输入入库数量");
            return;
        }

        if (!mPrinterUtil.selectPrinterCheck()) {
            showMessage("打印机未连接");
            return;
        }

        String jsonData = "{\n" +
                "  \"mid\": 0,\n" +
                "  \"mtid\": " + this.item.getMtid() + ",\n" +
                "  \"spid\": " + item.getSpid() + ",\n" +
                "  \"instorestatus\": 0,\n" +
                "  \"inid\": 0,\n" +
                "  \"picId\": 0,\n" +
                "  \"instoreuserid\": " + mSharedPreferencesHelper.getString(BaseConstants.UID) + ",\n" +
                "  \"InNum\": " + getRuKuShuLiang() + ",\n" +
                "  \"createtime\": \"" + ArmsUtils.getDataTime("yyyy-MM-dd HH:mm:ss") + "\",\n" +
                "  \"InstorePictures\": [\n" +
                "    {\n" +
                "      \"PictureId\": 0,\n" +
                "      \"PictureExtension\": \"jpg\",\n" +
                "      \"Picture\": \"" + mPic + "\"\n" +
                "    }\n" +
                "  ]\n" +
                "}";
        LogUtils.debugEInfo("jsonData==" + jsonData);
        RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"), jsonData);

        mPresenter.instore(body);
    }

    @Override
    public void chongXinDaYinErWeiMa(LiaoCheng_GongQiJu_RuKuCaoZuo.DataBean item) {
        if (!TextUtils.isEmpty(printData)) {
            showMessageNegativeDialog();
        } else {
            showMessage("请先入库，在打印二维码");
        }
    }

    private void showMessageNegativeDialog() {
        new QMUIDialog.MessageDialogBuilder(this)
                .setTitle("是否重新打印二维码")
                .setMessage("是否重新打印二维码？当前序号为" + printData)
                .addAction("取消", new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        dialog.dismiss();
                    }
                })
                .addAction(0, "确定", QMUIDialogAction.ACTION_PROP_NEGATIVE, new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        printBigQRcodeOriention(printData);
                        dialog.dismiss();
                    }
                })
                .create(mCurrentDialogStyle).show();
    }

    @NotNull
    private String getRuKuShuLiang() {
        return xetRuKuShuLiang.getText().toString().trim();
    }

    @Override
    public void onProgressInfo(String info) {

    }

    @Override
    public void onStateChange(String info) {

    }

    @Override
    public void onPrintProgress(String info) {

    }

    @Override
    public void onPrinterDiscovery(String info) {

    }

    @Override
    public void connectSuccess(String info) {

    }

    @Override
    public void Connecting(String info) {

    }

    @Override
    public void connectFail(String info) {

    }

    @Override
    public void printSuccess() {

    }

    @Override
    public void printFail() {

    }
}
